package com.ruoyi.business.service.impl;

import java.math.BigDecimal;
import java.util.List;

import com.ruoyi.business.domain.*;
import com.ruoyi.business.service.*;
import com.ruoyi.business.utils.SnGenerateUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.business.mapper.JtOrderMapper;
import com.ruoyi.common.core.text.Convert;

import javax.validation.constraints.NotEmpty;

/**
 * 订单Service业务层处理
 * 
 * @author Alan Zhang
 * @date 2025-03-29
 */
@Service
public class JtOrderServiceImpl implements IJtOrderService 
{
    private static final Logger log = LoggerFactory.getLogger(JtOrderServiceImpl.class);
    @Autowired
    private JtOrderMapper jtOrderMapper;
    @Autowired
    private IJtPaymentOrderService jtPaymentOrderService;
    @Autowired
    private IJtOrderOperateLogService jtOrderOperateLogService;
    @Autowired
    private IJtCommissionDetailService jtCommissionDetailService;
    @Autowired
    private IJtUserPromotionCodeRelService jtUserPromotionCodeRelService;
    @Autowired
    private IJtAppUserService jtAppUserService;
    @Autowired
    private IJtOutboundOrderService jtOutboundOrderService;

    /**
     * 查询订单
     * 
     * @param orderId 订单主键
     * @return 订单 明细
     */
    @Override
    public JtOrder selectJtOrderByOrderId(Long orderId)
    {
        return jtOrderMapper.selectJtOrderByOrderId(orderId);
    }

    /**
     * 查询订单
     *
     * @param orderId 订单主键
     * @return 订单
     */
    public JtOrder selectOrderInfoByOrderId(Long orderId){
        return jtOrderMapper.selectOrderInfoByOrderId(orderId);
    }

    /**
     * 查询订单
     *
     * @param orderNo 订单号
     * @return 订单
     */
    @Override
    public JtOrder selectJtOrderByOrderNo(String orderNo){
        return jtOrderMapper.selectJtOrderByOrderNo(orderNo);
    }

    /**
     * 查询订单列表
     * 
     * @param jtOrder 订单
     * @return 订单
     */
    @Override
    public List<JtOrder> selectJtOrderList(JtOrder jtOrder)
    {
        return jtOrderMapper.selectJtOrderList(jtOrder);
    }

    /**
     * 查询订单列表
     *
     * @param jtOrder 订单
     * @return 订单集合
     */
    @Override
    public List<JtOrder> selectJtOrderAndItemList(JtOrder jtOrder){
        return jtOrderMapper.selectJtOrderAndItemList(jtOrder);
    }

    /**
     * 新增订单
     * 
     * @param jtOrder 订单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertJtOrder(JtOrder jtOrder)
    {
        jtOrder.setCreateTime(DateUtils.getNowDate());
        int rows = jtOrderMapper.insertJtOrder(jtOrder);
        insertJtOrderItem(jtOrder);
        return rows;
    }

    /**
     * 修改订单
     * 
     * @param jtOrder 订单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateJtOrder(JtOrder jtOrder)
    {
        jtOrder.setUpdateBy(jtOrder.getUpdateBy());
        jtOrder.setUpdateTime(DateUtils.getNowDate());
        return jtOrderMapper.updateJtOrder(jtOrder);
    }

    /**
     * 修改订单
     *
     * @param jtOrder 订单
     * @return 结果
     */
    @Transactional
    @Override
    public int editJtOrder(JtOrder jtOrder)
    {
        jtOrder.setUpdateBy(jtOrder.getUpdateBy());
        jtOrder.setUpdateTime(DateUtils.getNowDate());
        jtOrderMapper.deleteJtOrderItemByOrderId(jtOrder.getOrderId());
        insertJtOrderItem(jtOrder);
        return jtOrderMapper.updateJtOrder(jtOrder);
    }

    /**
     * 批量删除订单
     * 
     * @param orderIds 需要删除的订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteJtOrderByOrderIds(String orderIds)
    {
        jtOrderMapper.deleteJtOrderItemByOrderIds(Convert.toStrArray(orderIds));
        return jtOrderMapper.deleteJtOrderByOrderIds(Convert.toStrArray(orderIds));
    }

    /**
     * 删除订单信息
     * 
     * @param orderId 订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteJtOrderByOrderId(Long orderId)
    {
        jtOrderMapper.deleteJtOrderItemByOrderId(orderId);
        return jtOrderMapper.deleteJtOrderByOrderId(orderId);
    }

    /**
     * 新增订单明细信息
     * 
     * @param jtOrder 订单对象
     */
    public void insertJtOrderItem(JtOrder jtOrder)
    {
        List<JtOrderItem> jtOrderItemList = jtOrder.getJtOrderItemList();
        Long orderId = jtOrder.getOrderId();
        if (StringUtils.isNotNull(jtOrderItemList))
        {
            List<JtOrderItem> list = new ArrayList<JtOrderItem>();
            for (JtOrderItem jtOrderItem : jtOrderItemList)
            {
                jtOrderItem.setOrderId(orderId);
                jtOrderItem.setCreateBy(jtOrder.getCreateBy());
                jtOrderItem.setCreateTime(DateUtils.getNowDate());
                list.add(jtOrderItem);
            }
            if (list.size() > 0)
            {
                jtOrderMapper.batchJtOrderItem(list);
            }
        }
    }

    /**
     * 订单发货
     * @param jtOrder
     * @return
     */
    @Transactional
    @Override
    public AjaxResult delivery(JtOrder jtOrder){
        JtOrder jtOrderDb = selectJtOrderByOrderId(jtOrder.getOrderId());
        if(jtOrderDb.getOrderStatus() != 1){
            return AjaxResult.error(jtOrderDb.getOrderStatus() + "订单此状态下不能发货！");
        }
        AjaxResult res = jtOutboundOrderService.outboundByOrderId(jtOrder.getOrderId());
        if(!res.isSuccess()){
            throw new BaseException(res.get("msg").toString());
        }
        jtOrder.setDvyTime(DateUtils.getNowDate());
        jtOrder.setOrderStatus(2);
        jtOrder.setUpdateBy(ShiroUtils.getSysUser().getUserName());
        jtOrder.setUpdateTime(DateUtils.getNowDate());
        int rows = updateJtOrder(jtOrder);
        if(rows > 0){
            //写日志
            JtOrderOperateLog log = new JtOrderOperateLog();
            log.setOperator(ShiroUtils.getSysUser().getUserName());
            log.setOrderId(jtOrderDb.getOrderId());
            //0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
            log.setOrderStatus(2);
            StringBuilder sbNote = new StringBuilder();
            sbNote.append("快递公司：").append(jtOrder.getLogisticsCompany()).append("，")
                    .append("快递单号：").append(jtOrder.getTrackingNumber());
            log.setNote(sbNote.toString());
            jtOrderOperateLogService.insertJtOrderOperateLog(log);

            return AjaxResult.success("订单发货成功！");
        } else {
            return AjaxResult.error("订单发货失败");
        }
    }


    /**
     * 手工支付 订单信息
     * Manual payment
     * @param jtOrder 订单
     * @return 结果
     */
    @Transactional
    @Override
    public AjaxResult manualPayment(JtOrder jtOrder, String transactionNo)
    {
        JtOrder jtOrderDb = selectOrderInfoByOrderId(jtOrder.getOrderId());
        if(jtOrderDb.getOrderStatus() != 0){
            return AjaxResult.error(jtOrderDb.getOrderStatus() + "订单此状态下不能支付！");
        }
        if(jtOrderDb.getIsPayed() != 0){
            return AjaxResult.error(jtOrderDb.getOrderNo() +"，订单已支付!");
        }

        List<Long> paymentIdList = jtPaymentOrderService.selectJtPaymentOrderByTradeNo(transactionNo);
        if(paymentIdList.size() > 0){
            return AjaxResult.error(transactionNo + "交易单号，已存在！");
        }
        if(jtOrder.getPaymentAmount() == null){
            return AjaxResult.error(transactionNo + "支付金额不能空！");
        }
        if(jtOrder.getPaymentAmount().compareTo(jtOrderDb.getOrderAmount()) != 0){
            return AjaxResult.error(jtOrderDb.getOrderNo() + " 输入的支付金额不一致！");
        }
        JtPaymentOrder paymentOrderParam = new JtPaymentOrder();
        paymentOrderParam.setOrderId(jtOrder.getOrderId());
        paymentOrderParam.setPaymentStatus(1);
        List<JtPaymentOrder> paymentOrderList = jtPaymentOrderService.selectJtPaymentOrderList(paymentOrderParam);
        //0待支付 1已支付 2支付取消 3支付异常
        if(paymentOrderList.size() > 0){
            return AjaxResult.error(jtOrderDb.getOrderNo() +" 订单已支付!");
        }
        Object remarkobj = jtOrder.getParams().get("remark");
        String remark ="";
        if(remarkobj != null) {
            remark = (String) remarkobj;
        }

        paymentOrderParam.setPaymentStatus(0);
        paymentOrderList = jtPaymentOrderService.selectJtPaymentOrderList(paymentOrderParam);
        if(paymentOrderList.size() > 0){
            if(paymentOrderList.size() >1){
                return AjaxResult.error(jtOrderDb.getOrderNo() +"，订单存在多条支付单记录!");
            }
            JtPaymentOrder jtPaymentOrder = paymentOrderList.get(0);
            jtPaymentOrder.setPaymentId(jtPaymentOrder.getPaymentId());
            jtPaymentOrder.setTradeNo(transactionNo);
            jtPaymentOrder.setPaymentMethod(1);//线下支付
            jtPaymentOrder.setPaymentStatus(1);
            jtPaymentOrder.setPayTime(DateUtils.getNowDate());
            jtPaymentOrder.setPaymentAmount(jtOrder.getPaymentAmount());
            jtPaymentOrder.setSubject(remark);
            jtPaymentOrderService.updateJtPaymentOrder(jtPaymentOrder);
        } else {
            JtPaymentOrder jtPaymentOrder = new JtPaymentOrder();
            jtPaymentOrder.setTradeNo(transactionNo);
            jtPaymentOrder.setOrderId(jtOrderDb.getOrderId());
            jtPaymentOrder.setOrderNo(jtOrderDb.getOrderNo());
            jtPaymentOrder.setUserId(jtOrderDb.getUserId());//设置用户
            //生成支付交易单号
            jtPaymentOrder.setPaymentNo(SnGenerateUtil.generatePaymentNumber());
            jtPaymentOrder.setPaymentMethod(1);//线下支付
            jtPaymentOrder.setPaymentStatus(1);//已支付
            jtPaymentOrder.setCurrency(jtOrderDb.getCurrency());
            jtPaymentOrder.setPaymentAmount(jtOrder.getPaymentAmount());
            jtPaymentOrder.setPayTime(DateUtils.getNowDate());

            jtPaymentOrder.setCreateBy(ShiroUtils.getSysUser().getUserName());
            jtPaymentOrder.setCreateTime(DateUtils.getNowDate());
            jtPaymentOrder.setSubject(remark);
            jtPaymentOrderService.insertJtPaymentOrder(jtPaymentOrder);
        }
        jtOrder.setPaymentTime(DateUtils.getNowDate());
        jtOrder.setIsPayed(1);//已支付
        jtOrder.setOrderStatus(1);
        jtOrder.setUpdateBy(ShiroUtils.getSysUser().getUserName());
        jtOrder.setUpdateTime(DateUtils.getNowDate());

        int rows = jtOrderMapper.updateJtOrder(jtOrder);
        if(rows > 0) {
            jtOrderDb = selectOrderInfoByOrderId(jtOrder.getOrderId());
            //计入佣金
           AjaxResult ajaxResult = calcCommission(jtOrderDb);

            //写日志
            JtOrderOperateLog log = new JtOrderOperateLog();
            log.setOperator(ShiroUtils.getSysUser().getUserName());
            log.setOrderId(jtOrderDb.getOrderId());
            //0->待付款；1->已付款；2->已发货；3->已完成；4->已关闭；
            log.setOrderStatus(1);
            StringBuilder sbNote = new StringBuilder();
            sbNote.append("手工支付：").append(transactionNo).append("，")
                    .append("金额：").append(jtOrder.getCurrency()).append(jtOrder.getPaymentAmount());
            log.setNote(sbNote.toString());
            jtOrderOperateLogService.insertJtOrderOperateLog(log);

            return AjaxResult.success("手工支付成功！");
        } else {
            return AjaxResult.error("手工支付失败！");
        }
    }


    /**
     * 产生佣金
     * @param jtOrder
     * @return
     */
    public AjaxResult calcCommission(JtOrder jtOrder){
        if(jtOrder.getUserId() == null){
            return AjaxResult.error("订单用户不存在！");
        }
        if(jtOrder.getPaymentAmount() == null){
            return AjaxResult.error("订单支付金额不能为空！");
        }
        //被绑定用户订单
        JtUserPromotionCodeRel param = new JtUserPromotionCodeRel();
        param.setUserId(jtOrder.getUserId());
        List<JtUserPromotionCodeRel> userPromotionCodeRelList = jtUserPromotionCodeRelService.selectJtUserPromotionCodeRelList(param);
        //存在绑定关系
        if(userPromotionCodeRelList.size() > 0){
            JtUserPromotionCodeRel userPromotionCodeRel = userPromotionCodeRelList.get(0);

            BigDecimal commission = jtOrder.getPaymentAmount().multiply(BigDecimal.valueOf(0.01));
            log.error("用户ID:{} 产生佣金{}", jtOrder.getUserId(), commission);
            JtAppUser jtAppUserDb = jtAppUserService.selectJtAppUserByUserId(userPromotionCodeRel.getOwnerUserId());
            //更新账户 佣金
            JtAppUser jtAppUser = new JtAppUser();
            jtAppUser.setUserId(jtAppUserDb.getUserId());
            BigDecimal userCommission;
            if(jtAppUserDb.getCommission() == null){
                userCommission = BigDecimal.ZERO;
            } else {
                userCommission = jtAppUserDb.getCommission();
            }
            userCommission = userCommission.add(commission);
            jtAppUser.setCommission(userCommission);
            int rows = jtAppUserService.updateJtAppUser(jtAppUser);
            if(rows > 0) {
                //产生佣金明细
                JtCommissionDetail jtCommissionDetail = new JtCommissionDetail();
                jtCommissionDetail.setUserId(jtAppUserDb.getUserId());
                jtCommissionDetail.setCurrency(jtOrder.getCurrency());
                jtCommissionDetail.setOrderNo(jtOrder.getOrderNo());
                jtCommissionDetail.setOrderAmount(jtOrder.getPaymentAmount());
                jtCommissionDetail.setOrderId(jtOrder.getOrderId());
                jtCommissionDetail.setAmount(commission);
                jtCommissionDetail.setStatus(1);
                jtCommissionDetail.setCreateBy(userPromotionCodeRel.getPromotionCode());
                jtCommissionDetail.setBalance(userCommission);
                jtCommissionDetailService.insertJtCommissionDetail(jtCommissionDetail);

                return AjaxResult.success();
            } else {
                log.error("用户ID:{}  执行结果:{}，产生佣金失败", jtOrder.getUserId(), rows);
                return AjaxResult.error("产生佣金失败");
            }
        } else {
            log.error("用户ID:{}，无绑定关系", jtOrder.getUserId());
            return AjaxResult.error("无绑定关系");
        }
    }


    /**
     * 统计订单数
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public Long selectOrderCount(@NotEmpty String startDate, @NotEmpty String endDate){
        return jtOrderMapper.selectOrderCount(startDate, endDate);
    }
}
